<template>
    <div class="common-container">
      <div class="header">
        <div class="header_left">
          <el-input v-model="search_val" placeholder="请输入建筑物名称" clearable @clear="clearNickname" size="small"
            style="width: 220px;">
            <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick">
            </el-button>
          </el-input>
  
        </div>
        <div class="header_right">
          <el-button size="small" style="margin-left: 15px;" icon="el-icon-plus" @click="onAdd" v-if="orgInfo.orgId">新增</el-button>
          <!-- <el-button size="small" class="el_button" @click="importClick" icon="el-icon-download">导入</el-button> -->
          <el-dropdown @command="onDropdown">
            <el-button size="small" style="margin-left: 15px;">
              批量操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <!-- <el-dropdown-item command="batch">批量操作</el-dropdown-item> -->
              <el-dropdown-item command="set">一键布防</el-dropdown-item>
              <el-dropdown-item command="remove">一键撤防</el-dropdown-item>
              <!-- <el-dropdown-item command="onimport">批量编辑</el-dropdown-item> -->
              <!-- <el-dropdown-item command="alarmReceiver">设置接警人管理</el-dropdown-item>
              <el-dropdown-item command="del">批量删除</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="content">
        <el-table :data="tableData" height="calc(100% - 65px)" class="table" @selection-change="batchSelect"
          :header-cell-style="headerStyle" row-key="id" ref="refMultipleTable" v-loading="loadingTable"
          element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)">
          <el-table-column align="center" type="selection" :reserve-selection="true" min-width="40">
          </el-table-column>
          <el-table-column align="center" label="序号" type="index" width="50">
          </el-table-column>
          <el-table-column align="center" prop="name" label="建筑物名称"  show-overflow-tooltip>
          </el-table-column>
          <el-table-column align="center" prop="floorCount" label="楼层数" >
            <template slot-scope="{ row }">
              <span @click="searchSpaceClick(row)" class="search_space">{{ row.floorCount }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="spaceCount" label="安装点" >
            <template slot-scope="{ row }">
              <span @click="SpaceClick(row)" class="search_space">{{ row.spaceCount }}</span>
            </template>
          </el-table-column>
  
          <el-table-column align="center" prop="orgName" label="联网单位"  show-overflow-tooltip>
          </el-table-column>

          <el-table-column align="center" prop="address" label="地址" min-width="140" show-overflow-tooltip>
          </el-table-column>
  
          <el-table-column align="center" prop="village" label="小区"  show-overflow-tooltip>
          </el-table-column>
  
          <el-table-column align="center" prop="management" label="操作" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="布防" placement="bottom">
                <i @click="onSet(scope.row)" class="iconfont anquan1 tableBtnIcon"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="撤防" placement="bottom">
                <i @click="onRemove(scope.row)" class="iconfont iconfontquxiaoshouquan tableBtnIcon"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
                <i @click="onEdit(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
                <i @click="onDel(scope.row.id)" class="iconfont shanchu tableBtnIcon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="page" :limit.sync="limit" @pagination="SpaceManager" class="pagination" />
      </div>
      <addModel ref="refAdd" :getLocationInfo="getLocationInfo" :getAddressflag="getAddressflag" :orgInfo="orgInfo"></addModel>
      <editModel ref="refEdit" :getLocationInfo="getLocationInfo" :editInfo='editInfo' :getAddressflag="getAddressflag">
      </editModel>
      <ImportBuildings ref="refImportBuildings"></ImportBuildings>
    </div>
  </template>
  
  <script>
  import addModel from "./component/addModel.vue";
  import editModel from "./component/editModel.vue";
  import ImportBuildings from "./component/ImportBuildings.vue";
  import tableStyleMixin from "@mixin/table-style";
  import Pagination from "@components/Pagination.vue";
  import {
    reqSpaceManager,
    reqDel,
    reqUpdate,
    reqOrgList,
    reqBatchDefence,
  } from "@/api/api";
  import { mapState } from "vuex";
  // import treeselect from "@riophae/vue-treeselect"; //树形选择器
  // import "@components/vue-treeselect.less"; //树形选择器
  // import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
  import loadMore from "@mixin/loadMore";
  import { jsonp } from 'vue-jsonp'//使用jsonp
  
  export default {
    props:['orgInfo'],
    name: "org-list",
    components: {
      Pagination,
      addModel,
      editModel,
      ImportBuildings,
      // treeselect,
    },
    mixins: [tableStyleMixin, loadMore],
    data() {
      return {
        normalizer(node) {
          return {
            id: node.id,
            label: node.orgName,
            children: node.children,
          };
        },
        getAddressflag: false,//地图选点
        loading: false,
        loadingSearch: false, //查询按钮loading
        search_val: "",
        page: 1,
        limit: 10,
        total: 0,
        tableData: [],
        loadingTable:false,
        getLocationInfo: {
          getLat: "",
          getLng: "",
          getAdd: "",
          province: "",
          city: "",
          area: "",
          provinceCityAreaValue: "",
        },
        editInfo: {},
        batchDate: [],
        projectList: [], //单位数据
        sysInstanceIndex: 1,
        sysInstanceTotalPages: 10,
        flag: true,
        selectedValue: "",
        orgName: ""
      };
    },
    mounted() {
    },
    computed: {
      ...mapState(["user"]),
    },
    methods: {
      // 清空
      handleClear() {
        this.selectedValue = '';
        this.orgName = '';
        this.sysInstanceIndex = 1;
        this.sysInstanceTotalPages = 10;
        this.projectList = []
        this.OrgList()
      },
      // 远程搜索
      async remoteMethod(query) {
        this.selectedValue = query //保留输入的值
        this.orgName = query //保留输入的值
        this.sysInstanceIndex = 1;
        this.sysInstanceTotalPages = 10;
        this.projectList = []
        this.OrgList()
      },
      async loadMore() {
        if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10)) return
        this.sysInstanceIndex++
        this.loading = true;
        // 获取列表数据的方法
        await this.OrgList()
        this.loading = false;
      },
      // 获取单位列表
      async OrgList() {
        var res = await reqOrgList({
          userId: this.user.userId,
          roleName: this.user.roleName,
          tenantId: this.user.tenantId,
          orgName: this.orgName
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.projectList = res.data.rows
      },
      // 下拉请求列表
      enterpriseChange(val) {
        if (val && this.flag) {
          this.OrgList();
          this.flag = false;//只执行一次
        }
      },
      // 建筑物点击楼层数量
      searchSpaceClick(row) {
        // console.log(row);
        this.$emit('getFloor',row)
      },
       // 建筑物点击安装点数量
      SpaceClick(row){
        this.$emit('getMounting',row)
      },
      // 清空
      clearNickname() {
        this.page = 1;
        this.limit = 10;
        this.SpaceManager();
      },
      //查询
      async searchClick() {
        this.page = 1;
        this.limit = 10;
        this.loadingSearch = true;
        await this.SpaceManager();
        this.loadingSearch = false;
      },
  
      // 监听获取经纬度
      addListenAddress() {
        window.addEventListener(
          "message",
          (event) => {
            // console.log(event);
            // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
            let loc = event.data;
            // console.log(loc);
            // console.log(loc.module);
            if (loc && loc.module == "locationPicker") {
              //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
              // console.log(loc, "loc");
              this.getAddress(loc.latlng.lat, loc.latlng.lng, loc.poiname);
              // this.isShowMap = false
            }
          },
          false
        );
      },
      // 获取地址信息
      getAddress(lat, lng, poiname) {
        jsonp(
          `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53`,
          {
            output: "jsonp",
          }
        )
          .then((res) => {
            // console.log(res);
            this.getAddressflag = !this.getAddressflag;
            let { province, city, district } = res.result.ad_info;
            let { title } = res.result.address_reference.town;
            // console.log(res.result, "res.result.ad_info");
            this.$set(this.getLocationInfo, "getLat", lat);
            this.$set(this.getLocationInfo, "getLng", lng);
            this.$set(this.getLocationInfo, "province", province);
            this.$set(this.getLocationInfo, "city", city);
            this.$set(this.getLocationInfo, "district", district);
            this.$set(this.getLocationInfo, "street", title);
            // 详细位置
            this.$set(
              this.getLocationInfo,
              "getAdd",
              this.stripscript(poiname).length > 20
                ? this.stripscript(poiname).substr(0, 20)
                : this.stripscript(poiname)
            );
          })
          .catch((err) => {
            // console.log(err, "err");
          });
      },
      // 过滤特殊字符
      stripscript(s) {
        let pattern = new RegExp(
          "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]"
        );
        let rs = "";
        for (let i = 0; i < s.length; i++) {
          rs = rs + s.substr(i, 1).replace(pattern, "");
        }
        return rs;
      },
      // 选择复选框批量添加联系人
      batchSelect(arr) {
        this.batchDate = [];
        // this.exportList = [];
        // this.exportList = arr;
        arr.forEach((c) => {
          this.batchDate.push(c.id);
        });
        // console.log(this.batchDate, "this.batchDate");
      },
      // 更多操作回调事件
      onDropdown(e) {
        switch (e) {
          case "batch":
            this.$refs.refBatch.dialogVisible = true;
            break;
          case "set":
            if (this.batchDate.length <= 0) {
              this.$modal.notifyWarning("请勾选要操作的建筑物");
              return;
            }
            this.$confirm(
              "一键布防将对该建筑物下所有楼层及安装点同时进行布防，确认后将更新该建筑物下所有楼层及安装点为布防状态。",
              "建筑物批量布防",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(async () => {
                const res = await reqBatchDefence({
                  spaceIdList: this.batchDate,
                  isDefence: 1,
                });
                if (res.code !== 20000)
                  return this.$modal.notifyWarning(res.message);
                this.$modal.notifySuccess("批量设置布防成功!");
                this.SpaceManager();
                this.clearSelections(); //清空复选框
              })
              .catch(() => { });
            break;
          case "remove":
            if (this.batchDate.length <= 0) {
              this.$modal.notifyWarning("请勾选要操作的建筑物");
              return;
            }
            this.$confirm(
              "一键撤防将对该建筑物下所有楼层及安装点同时进行撤防，确认后将更新该建筑物下所有楼层及安装点为撤防状态。",
              "建筑物批量撤防",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(async () => {
                const res = await reqBatchDefence({
                  spaceIdList: this.batchDate,
                  isDefence: 0,
                });
                if (res.code !== 20000)
                  return this.$modal.notifyWarning(res.message);
                this.$modal.notifySuccess("批量设置撤防成功!");
                this.SpaceManager();
                this.clearSelections(); //清空复选框
              })
              .catch(() => { });
            break;
          case "onimport":
            this.$refs.refImportBuildings.OrgList();
            this.$refs.refImportBuildings.dialogVisible = true;
            break;
          case "del":
          case "alarmReceiver":
            this.$refs.refAlarmReceiver.dialogVisible = true;
            break;
          case "del":
          // console.log("del");
        }
      },
      // 清空复选框√√
      clearSelections() {
        this.$refs.refMultipleTable.clearSelection();
      },
      // 新增
      onAdd() {
        this.$refs.refAdd.dialogVisible = true;
        this.$refs.refAdd.closeEditDialog2();//防止出现表单验证
        this.$refs.refAdd.RegionList();
      },
      onSet(row) {
        // 布防
        this.$confirm("确定布防该建筑物吗？", "布防", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            row.isDefence = 1;
            const res = await reqUpdate(row);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("布防成功!");
            this.SpaceManager();
          })
          .catch(() => { });
      },
      onRemove(row) {
        // 撤防
        this.$confirm("确定撤防该建筑物吗？", "撤防", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            row.isDefence = 0;
            const res = await reqUpdate(row);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("撤防成功!");
            this.SpaceManager();
          })
          .catch(() => { });
      },
      onEdit(item) {
        //   console.log(item, "item");
        // this.getLocationInfo = item;
        this.editInfo = JSON.parse(JSON.stringify(item));
        this.$refs.refEdit.dialogVisible = true;
        this.$refs.refEdit.RegionList();
        this.$refs.refEdit.cityArr();
        this.$refs.refEdit.areaArr();
        this.$refs.refEdit.RegionLevelList();
        this.$refs.refEdit.communitylList();
      },
      onDel(id) {
        this.$confirm("此操作将永久删除该建筑物, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            let res = await reqDel({
              id,
              userId: this.user.userId
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("删除建筑物成功");
            this.SpaceManager();
          })
          .catch(() => { });
      },
      // 建筑物列表
      async SpaceManager() {
        this.loadingTable=true;
        let res = await reqSpaceManager(this.page, this.limit, {
          userId: this.user.userId,
          roleName: this.user.roleName,
          name: this.search_val,
          orgId: this.orgInfo.orgId,
          metaCode: 1,
          isStatistics: 1
        });
        this.loadingTable=false;
        //   console.log(res.data);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.tableData = res.data.rows;
        this.total = res.data.total;
      },
      //建筑物初始化
      clearinit(){
        this.tableData = [];
        this.total = 0;
        this.page = 1;
        this.limit = 10;
        this.search_val="";
        this.clearSelections() // 清空复选框√√
      },
    },
    created() {
    },
  };
  </script>
  
  <style scoped lang="less">
  @import url("~@views/style/tablePage.less");
  
  .header_left {
    display: flex;
  }
  
  // 查看关联安装点
  .search_space {
    padding: 0 10px;
    cursor: pointer;
  
    &:hover {
      color: #7367f0;
    }
  }
  
  ::v-deep .el-button--small {
    background: #7367f0;
    color: #fff;
    border: none;
  }
  
  // 下拉框加载开始
  .div_box {
    height: 276px;
    position: absolute;
    top: -1px;
    left: -1px;
    width: 100%;
    z-index: 9999;
  }
  
  ::v-deep .el-loading-mask {
    border-radius: 4px;
  }
  
  </style>